package controller;

import dao.UserDao;
import entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取登录表单提交过来的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String errorMsg = "";
        //设置能够正常登录得一个状态值
        Boolean isLogin = false;
        //调用userdao根据用户名查询用户，若用户存在，校验密码
        User user = null;
        user = userDao.selectUserByname(username);
        if (user==null){

            isLogin = false;
            errorMsg = "该用户未注册";
        }else {

            if (user.getPassword().equals(password)){
                isLogin = true;
            }else {
                isLogin = false;
                errorMsg = "密码错误";
            }
        }
        //根据用户能否正常登录进行页面跳转
        if (isLogin){
            //用户登录成功时，将用户信息存在session作用域中
            HttpSession session = request.getSession();
            session.setAttribute("login_user",user);
            System.out.println(user.getAvatar());
            //响应重定向跳转到主页面，地址变为/main
            response.sendRedirect("/main");
        }else {
            //请求转发跳转到失败页面，地址仍未/login，将错误信息条件request附加属性作用域中
            request.setAttribute("errorMsg",errorMsg);
            request.getRequestDispatcher("/error.jsp").forward(request,response);
        }


    }
}
